'use client'

import { useState } from "react"
import { Purchase, PurchaseStatus } from "@prisma/client"
import { EyeIcon, CheckCircleIcon } from "@heroicons/react/24/outline"
import { ViewInboundDialog } from "./view-inbound-dialog"
import { completeInbound } from "@/actions/inbound"

type SerializedPurchase = Omit<Purchase, 'totalAmount' | 'createdAt' | 'updatedAt'> & {
  totalAmount: string
  createdAt: string
  updatedAt: string
  supplier: {
    id: number
    name: string
    contact: string
    phone: string
    address: string
    status: boolean
  }
}

interface InboundItemProps {
  purchase: SerializedPurchase
  statusMap: Record<PurchaseStatus, string>
  statusColorMap: Record<PurchaseStatus, string>
}

export function InboundItem({ purchase, statusMap, statusColorMap }: InboundItemProps) {
  const [isViewOpen, setIsViewOpen] = useState(false)
  const [submitting, setSubmitting] = useState(false)

  const handleComplete = async () => {
    if (!confirm('确定要完成入库吗？')) return

    try {
      setSubmitting(true)
      const result = await completeInbound(purchase.id)
      if (!result.success) {
        alert(result.error)
      }
    } catch (error) {
      console.error('完成入库失败:', error)
      alert('完成入库失败')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <>
      <tr className="hover:bg-gray-50">
        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
          {purchase.code}
        </td>
        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
          {purchase.supplier.name}
        </td>
        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
          ¥{parseFloat(purchase.totalAmount).toFixed(2)}
        </td>
        <td className="px-6 py-4 whitespace-nowrap">
          <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
            purchase.status === 'PENDING' 
              ? 'bg-yellow-100 text-yellow-800'
              : purchase.status === 'COMPLETED'
              ? 'bg-green-100 text-green-800'
              : 'bg-red-100 text-red-800'
          }`}>
            {purchase.status === 'PENDING' ? '待入库' : 
             purchase.status === 'COMPLETED' ? '已入库' : '已取消'}
          </span>
        </td>
        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
          {new Date(purchase.createdAt).toLocaleString()}
        </td>
        <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
          <button
            onClick={() => setIsViewOpen(true)}
            className="text-blue-600 hover:text-blue-900 mr-4"
          >
            <EyeIcon className="h-5 w-5" />
          </button>
          {purchase.status === 'PENDING' && (
            <button
              onClick={handleComplete}
              disabled={submitting}
              className="text-green-600 hover:text-green-900 disabled:opacity-50"
            >
              <CheckCircleIcon className="h-5 w-5" />
            </button>
          )}
        </td>
      </tr>
      {isViewOpen && (
        <ViewInboundDialog
          purchase={purchase}
          open={isViewOpen}
          onClose={() => setIsViewOpen(false)}
        />
      )}
    </>
  )
} 